package com.sailorj.itools.action;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.sailorj.itools.common.GitRunnable;
import com.sailorj.itools.constants.SailorjConfigConstants;
import com.sailorj.itools.utils.AsyncUtil;
import com.sailorj.itools.utils.Logger;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.storage.file.FileRepositoryBuilder;

import java.io.IOException;
import java.nio.file.Paths;
import java.util.concurrent.*;

public class GitAction extends AnAction {

    @Override
    public void actionPerformed(AnActionEvent event) {
        try {
            //获取编辑器
            Editor mEditor = event.getData(PlatformDataKeys.EDITOR);
            if (mEditor == null) {
                Logger.info("编辑器获取失败");
                return;
            }

            // 获取当前项目对象
            Project project = event.getProject();
            String msg = "项目.git文件较大耗时会久,执行成功会弹窗.正在置后台处理,请稍等...";
            Logger.showPopupWindow(mEditor, msg);
            // 1.获取git操作对象
            String dir = project.getBasePath();
            // String dir = "D:\\Project\\gitlab\\rtmart-multi";
            String projectName = dir.substring(dir.lastIndexOf('/') + 1);
            Git git = null;
            Repository repository = null;
            try {
                repository = new FileRepositoryBuilder().setGitDir(Paths.get(dir, ".git").toFile()).build();
                git = new Git(repository);
            } catch (IOException e) {
                Messages.showMessageDialog(project, "目录获取异常, .git无权限访问或不存在", SailorjConfigConstants.title, Messages.getInformationIcon());
                return;
            }
            GitRunnable runnable = new GitRunnable(git, repository, projectName, mEditor, project);

            /**
            // 放到线程池
            ExecutorService es = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS,
                    new ArrayBlockingQueue<>(1), Executors.defaultThreadFactory(),
                    new ThreadPoolExecutor.DiscardPolicy()); // 直接丢弃任务 DiscardPolicy
            es.execute(runnable);
             **/
            AsyncUtil.run(runnable);
        } catch (Exception ex) {
            ex.printStackTrace();
            Logger.error("执行异常," + ex.getMessage());
        }
    }

    public static void main(String[] args) {
//        try {
        //提取某个作者的提交，并打印相关信息
//            Git git = Git.open(new File("D:\\Project\\gitlab\\rtmart-multi\\.git"));
//            DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            Iterable<RevCommit> results = git.log().setRevFilter(new RevFilter() {
//                @Override
//                public boolean include(RevWalk walker, RevCommit cmit)
//                        throws StopWalkException, MissingObjectException, IncorrectObjectTypeException, IOException {
//                    return cmit.getAuthorIdent().getName().equals("shengjun.huang");
//                }
//
//                @Override
//                public RevFilter clone() {
//                    return this;
//                }
//            }).call();
//            results.forEach(commit -> {
//                PersonIdent authoIdent = commit.getAuthorIdent();
//                System.out.println("提交人：  " + authoIdent.getName() + "     <" + authoIdent.getEmailAddress() + ">");
//                System.out.println("提交SHA1：  " + commit.getId().name());
//                System.out.println("提交信息：  " + commit.getShortMessage());
//                System.out.println("提交时间：  " + format.format(authoIdent.getWhen()));
//            });
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }

}
